//引入公共文件
import '@utils/init.js';

import ajax from '@utils/ajax.js'
//引入studentsAdd里获取专业和班级数据
import { renderClassesSelect, uploadImages } from "@js/studentsAdd"



//获取修改学生数据
renderUpdateStudents()

async function renderUpdateStudents() {
    const _id = location.search.split("?=")[1];
    const res = await ajax({
        url: '/students/updateStudents',
        type: 'POST',
        data: { _id },
    })
    if (res.code) {
        console.log('修改学生获取成功', res.result);
        $('#studentsName').val(res.result.name)
        $('#studentsAge').val(res.result.age)
        $(`[name=studentsGender][value=${res.result.gender}]`).prop('checked', true);
        $('#studentProfession').val(res.result.professionId);
        await renderClassesSelect();
        $(`#studentClass`).val(res.result.classesId);
        $('#showImages').prop('src', res.result.imagesPath)
        $('#updateBtn').attr('data-id', res.result._id)
    }
}
//修改学生专业change事件
$('#studentProfession').change(function() {
    const professionId = $(this).val();
    renderClassesSelect(professionId)
})

//修改图片
uploadImages()

//确认修改
$('#updateBtn').click(function() {
    const _id = $(this).data('id');
    const name = $('#studentsName').val()
    const age = $('#studentsAge').val()
    const gender = $(`[name=studentsGender]:checked`).val()
    const professionId = $('#studentProfession').val();
    const classesId = $('#studentClass').val()
    const imagesPath = $('#showImages').prop('src')
    console.log(_id, name, age, gender, professionId, classesId, imagesPath);
    $.ajax({
        url: '/api/students/amend',
        type: 'POST',
        data: {
            name,
            age,
            gender,
            professionId,
            classesId,
            _id,
            imagesPath
        },
        success(res) {
            if (res.code) {
                alert('学生修改成功')
            }
        }
    })
})